package com.hn.zhijian.system.rsasdk;

import org.apache.tomcat.util.codec.binary.StringUtils;

/**
 * RAS加/解密工具类
 *
 * @author shaohai.Liu
 * @version 0.0.1-SNAPSHOT
 * @date 2017-8-8
 */
public class RSAUtils {

    /**
     * 构造方法
     */
    private RSAUtils() {
        super();
    }

    /**
     * RSA加密
     *
     * @param plainText 明文
     * @param publicKey 公钥
     * @return 密文串
     * @throws SecurityException 加解密异常
     */
    public static String encrypt(final byte[] plainText, final String publicKey) throws SecurityException {
        final RSA rsa = new RSA();
        byte[] cipher = rsa.encrypt(rsa.loadPublicKeyByStr(publicKey), plainText);
        byte[] cipherCode = rsa.encode(cipher);
        return StringUtils.newStringUtf8(cipherCode);
    }

    /**
     * RSA加密
     *
     * @param plainText  明文
     * @param privateKey 私钥
     * @return 密文串
     * @throws SecurityException 加解密异常
     */
    public static String encryptByPri(final byte[] plainText, final String privateKey) throws SecurityException {
        final RSA rsa = new RSA();
        byte[] cipher = rsa.encrypt(rsa.loadPrivateKeyByStr(privateKey), plainText);
        byte[] cipherCode = rsa.encode(cipher);
        return StringUtils.newStringUtf8(cipherCode);
    }

    /**
     * RSA解密
     *
     * @param cipherText 密文
     * @param privateKey 私钥
     * @return 明文
     * @throws SecurityException 加解密异常
     */
    public static String decrypt(final byte[] cipherText, final String privateKey) throws SecurityException {
        final RSA rsa = new RSA();
        byte[] bytes = rsa.decrypt(rsa.loadPrivateKeyByStr(privateKey), rsa.decode(cipherText));
        return StringUtils.newStringUtf8(bytes).trim();
    }

    /**
     * RSA解密
     *
     * @param cipherText 密文
     * @param publicKey  公钥
     * @return 明文
     * @throws SecurityException 加解密异常
     */
    public static String decryptByPub(final byte[] cipherText, final String publicKey) throws SecurityException {
        final RSA rsa = new RSA();
        byte[] bytes = rsa.decrypt(rsa.loadPublicKeyByStr(publicKey), rsa.decode(cipherText));
        return StringUtils.newStringUtf8(bytes).trim();
    }
}
